<script setup>
import {onLoad,onShow,onUnload} from '@dcloudio/uni-app'
import {ref,getCurrentInstance} from 'vue'
import {reqOrderAddress,
reqOrderDetail,
reqBuyNow,
reqSubmitOrder,
reqBeforePayInfo,
reqWechatPayStatus} from '../api/orderPay.js'
import {xtzDebounce,timerId} from '../../utils/xtzDebounce.js'
const {proxy} = getCurrentInstance()
let routerGoodsId = ref()
onLoad((options)=>{
	// console.log(options);
	blessing.value=options.blessing
	routerGoodsId.value = options.goodsId
})
onShow(async()=>{
	await getOrderAddress()
	await getOrderDetail()
})
let blessing = ref('')
const orderAddress = ref({})
// 获取应用，挂载过滤的地址
const app = getApp()
// 获取收货地址
const getOrderAddress = async()=>{
	if(app.globalData.address.fullAddress){
		orderAddress.value = app.globalData.address
		return
	}
	const res = await reqOrderAddress()
	if(res.code===200){
		orderAddress.value = res.data
	}
	// console.log(orderAddress.value);
	// console.log(app.globalData);
}
const orderDetail = ref([])
let countSum = ref(0)
// 获取订单详情
const getOrderDetail = async()=>{
	// routerGoodsId.value为真是从商品详情里进入来的
	const res = routerGoodsId.value?await reqBuyNow({goodsId:routerGoodsId.value,blessing}):await reqOrderDetail()
	// console.log(res);
	if(res.code===200){
		orderDetail.value = res.data.cartVoList
		countSum.value = res.data.totalAmount
	} 	
	const orderItem = orderDetail.value.find((item)=>item.blessing!=='')
	if(orderItem){
		blessing.value = orderItem.blessing
	}else{
		blessing.value = '无'
	}
	// console.log(orderItem,blessing.value);
}
onUnload(()=>{
	app.globalData.address = {}
})
const ordererFormData = ref({
	name:'',
	phone:'',
	date:'',
	remark:''
})
// 选择日期
const dateChange=(e)=>{
	ordererFormData.value.date = e
}
const nameRegExp = '^[\\u4e00-\\u9fa5]{2,4}$'
const phoneRegExp = '^1[3-9]\\d{9}$'
const rules = {
	name:{
		rules:[
			{required:true,errorMessage:'姓名为必填项'},
			{format:'string',errorMessage:'类型必须为字符串'},
			{pattern:nameRegExp,errorMessage:'长度最少2个字最多3个字'},			
		]
	},
	phone:{
		rules:[
			{required:true,errorMessage:'电话为必填项'},
			{format:'string',errorMessage:'类型必须为字符串'},
			{pattern:phoneRegExp,errorMessage:'请输入正确的手机号'},
		]
	},
	date:{
		rules:[
			{required:true,errorMessage:'详细地址为必填项'}
		]
	},
	remark:{
		rules:[
			{required:true,errorMessage:'祝福语为必填项'}
		]
	}
}
// 表格的引用
const valiOrdererForm = ref({})
// 订单号 
let orderNumber = ref('')
// 提交订单
const submitOrder = async()=>{
	if(!orderAddress.value.id){
		proxy.$toast({title:'请选择地址'})
	}
	try{
		xtzDebounce(valiteTrue,800)()	
	}catch(e){
		console.log(e);
		return 
	}
}
const valiteTrue = async() =>{
	await valiOrdererForm.validate()
	const params ={
		buyName:ordererFormData.value.name,
		buyPhone:ordererFormData.value.phone,
		cartList:orderDetail.value,
		deliveryDate:ordererFormData.value.date,
		remarks:blessing.value,
		userAddressId:orderAddress.value.id
	}
	// console.log(params);
	const res = await reqSubmitOrder(params)
	if(res.code==200){
		orderNumber.value=res.data
		try{
			// 这里开始，个人开发者已经不起效了，往下只写逻辑
			await asvancePay(orderNumber.value)
		}catch(e){
			proxy.$toast({
				title:"支付失败，请联系客服",
				icon:'error'
			})
		}						
	}
}
// 获取预付订单信息，支付参数
const asvancePay=async(orderNumber)=>{
	const res = await reqBeforePayInfo(orderNumber)
	console.log(res);
	if(res.code===200){
		// 获取支付的结果
		const payInfo = await uni.requestPayment(res.data)
		if(payInfo.errMsg==='requestPayment:ok'){
			// 查询支付的状态
			const statusRes = reqWechatPayStatus(orderNumber)
			if(statusRes.code===200){
				uni.navigateTo({
					url:'/pagesPay/list/list'
				})
			}
		}
	}
}
</script>

<template>
	<view class="order-detail">
		<scroll-view scroll-y="true" >		
			<uni-list>
				<uni-list-item  show-arrow="true">
					<template v-slot:header>
						<view class="edit-address">
							<template v-if="orderAddress.fullAddress">
								<view class="full-address">{{orderAddress.fullAddress}}</view>
								<view class="name-phone">{{orderAddress.name}} {{orderAddress.phone}}</view>
							</template>
							<template v-else>
								<navigator url="/pagesSetting/address/list/list?flag=1" class="go-select-address">点我去选地址</navigator>		
							</template>						
						</view>							
					</template>
				</uni-list-item>
			</uni-list>
			<view class="orderer">
				<uni-forms ref="valiOrdererForm" :rules="rules" :modelValue="ordererFormData">
					<uni-forms-item label="订购人姓名:" name="name" :label-width="90">
						<uni-easyinput v-model="ordererFormData.name" placeholder="请输入姓名" :inputBorder="false"/>
					</uni-forms-item>
					<uni-forms-item label="订购人手机号:" name="phone" :label-width="100">
						<uni-easyinput v-model="ordererFormData.phone" placeholder="手机号" :inputBorder="false"/>
					</uni-forms-item>
					<uni-forms-item label="期望送达日期:" name="date" :label-width="100">
						<template #default>
							<uni-datetime-picker type="date"
							:clear-icon="false" 
							v-model="ordererFormData.date" 
							placeholder="请选择日期"
							@change="dateChange"
							:border="false"/>
						</template>
					</uni-forms-item>
					<uni-forms-item label="订单备注:" name="remark" :label-width="80">
						<uni-easyinput type="textarea" v-model="ordererFormData.remark" placeholder="祝福语"/>
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="orderGoodsList">
				<view class="cart-goods-card" v-for="item in orderDetail" v-bind:key="item.goodsId">
					<view class="l">
						<image class="goods-img" :src="item.imageUrl"></image>
					</view>
					<view class="r">
						<view class="tit" ref="inputs">{{item.name}}</view>
						<view class="count-price">
							<view class="price-yuan">￥<text class="yuan">{{item.price}}</text></view>
							<view class="count">
								{{item.count}}x
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>	
		<view class="countSum-submit">
			<view class="countSum">￥<text class="count-sum-price">{{countSum}}</text></view>
			<view class="submit-btn" @click="submitOrder(valiOrdererForm)">提交订单</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
:deep(.uni-date__x-input){
	color:#acacac;
	font-size: 30rpx;
}
// :deep(.uni-forms-item ){
// 	margin-bottom: 10rpx;
// }
.order-detail{
	padding: 20rpx 20rpx 88rpx 20rpx;
	.edit-address{
		font-size: 28rpx;
		.full-address{
			margin-bottom: 10rpx;
		}
		.name-phone{
			padding: 15rpx 0;
		}
	}
	.go-select-address{
		padding: 10rpx 0;
	}
	.orderer{
		background: white;
		margin:16rpx 0;
		padding:0 20rpx 1rpx;
	}
	.orderGoodsList{
		.cart-goods-card{
			background: white;
			padding: 20rpx;
			border-radius: 30rpx;
			display: flex;
			flex-direction: row;
			margin-bottom: 16rpx;
			.l{
				height: 200rpx;
				width: 200rpx;
				.goods-img{
					width: 100%;
					height: 100%;
				}
			}
			.r{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				flex:1;
				margin-left: 16rpx;
				.tit{
					font-size: 28rpx;
				}
				.count-price{
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					.price-yuan{
						color: #f3514f;
						.yuan{
							font-size: 36rpx;
							font-weight: bolder;
						}
					}
					.count{
						
					}
				}
			}
		}
	}
	.countSum-submit{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: white;
		padding: 10rpx 30rpx;
		.countSum{
			color: #f3514f;			
			font-weight: bold;
			.count-sum-price{
				font-size: 36rpx;
			}
		}
		.submit-btn{
			font-size: 28rpx;
			color: white;
			background: #f3514f;
			border-radius: 40rpx;
			width: 180rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			font-weight: bold;
		}
	}
}
</style>
